﻿using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command.Roles;
using MediatR;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler.Roles
{
    public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, APIResult<object>>
    {
        private readonly IBaseRepository<Role> roleRep;

        public UpdateRoleCommandHandler(IBaseRepository<Role> roleRep)
        {
            this.roleRep = roleRep;
        }
        public Task<APIResult<object>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();

            var obj = roleRep.GetAll().FirstOrDefault(x => x.RoleId == request.RoleId);

            obj.RoleName = request.RoleName;
            obj.UpdateName = request.UpdateName;
            obj.UpdateTime = DateTime.Now;
            var list = roleRep.GetAll().Where(x => x.RoleName == request.RoleName);
            if (list.Count() == 0)
            {
                roleRep.Update(obj);
                result.Code = APIEnum.修改成功;
                result.Msg = APIEnum.修改成功.ToString();
            }
            else
            {
                result.Code = APIEnum.用户名重复;
                result.Msg = APIEnum.用户名重复.ToString();
            }

            return Task.FromResult(result);
        }
    }
}
